<?php
/**
 * Core
 *  
 * @author Administrator
 * @version 
 */
class Model_Core{

    
    //获取客户IP
    public function convertip($ip) {
    
    	$return = '';
    
    	if(preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) {
    
    		$iparray = explode('.', $ip);
    
    		if($iparray[0] == 10 || $iparray[0] == 127 || ($iparray[0] == 192 && $iparray[1] == 168) || ($iparray[0] == 172 && ($iparray[1] >= 16 && $iparray[1] <= 31))) {
    			$return = '- LAN';
    		} elseif($iparray[0] > 255 || $iparray[1] > 255 || $iparray[2] > 255 || $iparray[3] > 255) {
    			$return = '- Invalid IP Address';
    		} else {
    			$tinyipfile = './data/ipdata/tinyipdata.dat';
    			$fullipfile = './data/ipdata/wry.dat';
    			if(@file_exists($tinyipfile)) {
    				$return = $this->convertip_tiny($ip, $tinyipfile);
    				$return = iconv("GB2312//IGNORE", "UTF-8", $return);
    			} elseif(@file_exists($fullipfile)) {
    				$return = $this->convertip_full($ip, $fullipfile);
    				$return = iconv("GB2312//IGNORE", "UTF-8", $return);
    			}
    		}
    	}
    
    	return $return;
    
    }
    
    protected function convertip_tiny($ip, $ipdatafile) {
    
    	static $fp = NULL, $offset = array(), $index = NULL;
    
    	$ipdot = explode('.', $ip);
    	$ip    = pack('N', ip2long($ip));
    
    	$ipdot[0] = (int)$ipdot[0];
    	$ipdot[1] = (int)$ipdot[1];
    
    	if($fp === NULL && $fp = @fopen($ipdatafile, 'rb')) {
    		$offset = @unpack('Nlen', @fread($fp, 4));
    		$index  = @fread($fp, $offset['len'] - 4);
    	} elseif($fp == FALSE) {
    		return  '- Invalid IP data file';
    	}
    
    	$length = $offset['len'] - 1028;
    	$start  = @unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
    
    	for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) {
    
    		if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip) {
    			$index_offset = @unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
    			$index_length = @unpack('Clen', $index{$start + 7});
    			break;
    		}
    	}
    
    	@fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
    	if($index_length['len']) {
    		return '- '.@fread($fp, $index_length['len']);
    	} else {
    		return '- Unknown';
    	}
    
    }
    
    protected function convertip_full($ip, $ipdatafile) {
    
    	if(!$fd = @fopen($ipdatafile, 'rb')) {
    		return '- Invalid IP data file';
    	}
    
    	$ip = explode('.', $ip);
    	$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
    
    	if(!($DataBegin = fread($fd, 4)) || !($DataEnd = fread($fd, 4)) ) return;
    	@$ipbegin = implode('', unpack('L', $DataBegin));
    	if($ipbegin < 0) $ipbegin += pow(2, 32);
    	@$ipend = implode('', unpack('L', $DataEnd));
    	if($ipend < 0) $ipend += pow(2, 32);
    	$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
    
    	$BeginNum = $ip2num = $ip1num = 0;
    	$ipAddr1 = $ipAddr2 = '';
    	$EndNum = $ipAllNum;
    
    	while($ip1num > $ipNum || $ip2num < $ipNum) {
    		$Middle= intval(($EndNum + $BeginNum) / 2);
    
    		fseek($fd, $ipbegin + 7 * $Middle);
    		$ipData1 = fread($fd, 4);
    		if(strlen($ipData1) < 4) {
    			fclose($fd);
    			return '- System Error';
    		}
    		$ip1num = implode('', unpack('L', $ipData1));
    		if($ip1num < 0) $ip1num += pow(2, 32);
    
    		if($ip1num > $ipNum) {
    			$EndNum = $Middle;
    			continue;
    		}
    
    		$DataSeek = fread($fd, 3);
    		if(strlen($DataSeek) < 3) {
    			fclose($fd);
    			return '- System Error';
    		}
    		$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
    		fseek($fd, $DataSeek);
    		$ipData2 = fread($fd, 4);
    		if(strlen($ipData2) < 4) {
    			fclose($fd);
    			return '- System Error';
    		}
    		$ip2num = implode('', unpack('L', $ipData2));
    		if($ip2num < 0) $ip2num += pow(2, 32);
    
    		if($ip2num < $ipNum) {
    			if($Middle == $BeginNum) {
    				fclose($fd);
    				return '- Unknown';
    			}
    			$BeginNum = $Middle;
    		}
    	}
    
    	$ipFlag = fread($fd, 1);
    	if($ipFlag == chr(1)) {
    		$ipSeek = fread($fd, 3);
    		if(strlen($ipSeek) < 3) {
    			fclose($fd);
    			return '- System Error';
    		}
    		$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
    		fseek($fd, $ipSeek);
    		$ipFlag = fread($fd, 1);
    	}
    
    	if($ipFlag == chr(2)) {
    		$AddrSeek = fread($fd, 3);
    		if(strlen($AddrSeek) < 3) {
    			fclose($fd);
    			return '- System Error';
    		}
    		$ipFlag = fread($fd, 1);
    		if($ipFlag == chr(2)) {
    			$AddrSeek2 = fread($fd, 3);
    			if(strlen($AddrSeek2) < 3) {
    				fclose($fd);
    				return '- System Error';
    			}
    			$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
    			fseek($fd, $AddrSeek2);
    		} else {
    			fseek($fd, -1, SEEK_CUR);
    		}
    
    		while(($char = fread($fd, 1)) != chr(0))
    			$ipAddr2 .= $char;
    
    		$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
    		fseek($fd, $AddrSeek);
    
    		while(($char = fread($fd, 1)) != chr(0))
    			$ipAddr1 .= $char;
    	} else {
    		fseek($fd, -1, SEEK_CUR);
    		while(($char = fread($fd, 1)) != chr(0))
    			$ipAddr1 .= $char;
    
    		$ipFlag = fread($fd, 1);
    		if($ipFlag == chr(2)) {
    			$AddrSeek2 = fread($fd, 3);
    			if(strlen($AddrSeek2) < 3) {
    				fclose($fd);
    				return '- System Error';
    			}
    			$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
    			fseek($fd, $AddrSeek2);
    		} else {
    			fseek($fd, -1, SEEK_CUR);
    		}
    		while(($char = fread($fd, 1)) != chr(0))
    			$ipAddr2 .= $char;
    	}
    	fclose($fd);
    
    	if(preg_match('/http/i', $ipAddr2)) {
    		$ipAddr2 = '';
    	}
    	$ipaddr = "$ipAddr1 $ipAddr2";
    	$ipaddr = preg_replace('/CZ88\.NET/is', '', $ipaddr);
    	$ipaddr = preg_replace('/^\s*/is', '', $ipaddr);
    	$ipaddr = preg_replace('/\s*$/is', '', $ipaddr);
    	if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
    		$ipaddr = '- Unknown';
    	}
    
    	return '- '.$ipaddr;
    
    }
    
    //IP TO CITY NAME
    protected function ip_name($ip){
        $return = '';
        
        $data = $this->convertip($ip);
        if ($data){
            //取省
            if (strpos($data, '北京')){
                $get_province    = '北京';
                $get_province_id = 1;
            }elseif(strpos($data, '天津')) {
                $get_province    = '天津';
                $get_province_id = 2;
            }elseif (strpos($data, '河北')) {
               	$get_province    = '河北';
                $get_province_id = 3;
            }elseif (strpos($data, '山西')) {
                $get_province    = '山西';
                $get_province_id = 4;
            }elseif (strpos($data, '内蒙古')) {
                $get_province    = '内蒙古';
                $get_province_id = 5;
            }elseif (strpos($data, '辽宁')) {
                $get_province    = '辽宁';
                $get_province_id = 6;
            }elseif (strpos($data, '吉林')) {
                $get_province    = '吉林';
                $get_province_id = 7;
            }elseif (strpos($data, '黑龙江')) {
                $get_province    = '黑龙江';
                $get_province_id = 8;
            }elseif (strpos($data, '上海')) {
                $get_province    = '上海';
                $get_province_id = 9;
            }elseif(strpos($data, '江苏')) {
            	$get_province    = '江苏';
            	$get_province_id = 10;
            }elseif (strpos($data, '浙江')) {
            	$get_province    = '浙江';
            	$get_province_id = 11;
            }elseif (strpos($data, '安徽')) {
            	$get_province    = '安徽';
            	$get_province_id = 12;
            }elseif (strpos($data, '福建')) {
            	$get_province    = '福建';
            	$get_province_id = 13;
            }elseif (strpos($data, '江西')) {
            	$get_province    = '江西';
            	$get_province_id = 14;
            }elseif (strpos($data, '山东')) {
            	$get_province    = '山东';
            	$get_province_id = 15;
            }elseif (strpos($data, '河南')) {
            	$get_province    = '河南';
            	$get_province_id = 16;
            }elseif (strpos($data, '湖北')) {
            	$get_province    = '湖北';
            	$get_province_id = 17;
           	}elseif (strpos($data, '湖南')) {
            	$get_province    = '湖南';
            	$get_province_id = 18;
            }elseif (strpos($data, '广东')) {
            	$get_province    = '广东';
            	$get_province_id = 19;
            }elseif (strpos($data, '广西')) {
            	$get_province    = '广西';
            	$get_province_id = 20;
            }elseif (strpos($data, '海南')) {
            	$get_province    = '海南';
            	$get_province_id = 21;
            }elseif (strpos($data, '重庆')) {
            	$get_province    = '重庆';
            	$get_province_id = 22;
            }elseif (strpos($data, '四川')) {
            	$get_province    = '四川';
            	$get_province_id = 23;
            }elseif (strpos($data, '贵州')) {
            	$get_province    = '贵州';
            	$get_province_id = 24;
            }elseif (strpos($data, '云南')) {
            	$get_province    = '云南';
            	$get_province_id = 25;
            }elseif (strpos($data, '陕西')) {
            	$get_province    = '陕西';
            	$get_province_id = 27;
            }elseif (strpos($data, '甘肃')) {
            	$get_province    = '甘肃';
            	$get_province_id = 28;
            } else {
            	$get_province    = '';
            	$get_province_id = 0;
            }
            //取市
            if (strpos($data, '南京')) {
            	$get_city    = '南京';
            	$get_city_id = 162;
            }elseif (strpos($data, '无锡')){
            	$get_city    = '无锡';
            	$get_city_id = 163;
            }elseif (strpos($data, '盐城')){
            	$get_city    = '盐城';
            	$get_city_id = 170;
            }elseif (strpos($data, '广州')){
            	$get_city    = '广州';
            	$get_city_id = 289;
            }elseif (strpos($data, '深圳')){
            	$get_city    = '深圳';
            	$get_city_id = 291;
            }else {
            	$get_city    = '';
            	$get_city_id = 0;
            }
            $return[province] = array("id"=>"$get_province_id", "name"=>"$get_province");
            if ($get_province == "") {
                $return[province] = array("id"=>"-1", "name"=>"全国");
            }
            $return[city] = array("id"=>"$get_city_id", "name"=>"$get_city");
        }
        
        return $return;
    }
    
    
    //GET 、 SESSION 、 IP
    public function getNowCity($city_id, $ip){
        
        $tcl_session = new Zend_Session_Namespace('taochele');
        $city_db = new Model_City();
        if ($city_id) {
            // GET CHANGE
        	if ($city_id == -1) {
        		$results[city_id] = -1;
        		$results[city_name] = "全国";
        	}else{
        		$city_arr = $city_db->getCity($city_id);
        		$results[city_id] = $city_id;
        		$results[city_name] = substr($city_arr[name], 0, 6);
        	}
        	//SET SESSION
        	$tcl_session->city_id = $results[city_id];
        	$tcl_session->city_name = $results[city_name];
        	
        }elseif ($tcl_session->city_id){
            // SESSION CHANGE
            $results[city_id] = $tcl_session->city_id;
            $results[city_name] = $tcl_session->city_name;
        }else{
        	// IP CHANGE
        	$city_ip = $this->ip_name($ip);
        	if ($city_arr[city][id] == 0) {
        	    //list()
        	    $results[city_id] = $city_ip[province][id];
        		$results[city_name] = $city_ip[province][name];
        	}else{
        		$results[city_name] = $city_ip[city][name];
        		$results[city_id] = $city_ip[city][id];
        	}
        }
        return $results;
    }
    
    
    // NAV 
    public function getNav($controller, $action, $res){
		$results = "";
		//导航数据未入库  在CONTROLLER中直接输出 NAV
		/*
		 *     
	<li><span class="divider">/</span>xx </li>
    <li class="active"><span class="divider">/</span>我要买车 </li>
		 * */        
    	return $results;
    }

    //多页码分页 
    public function html_multi($page, $howpage, $url, $adjacents=4) {
    	
        
    	$repage	   = "<li><a href=\"".$url.($page-1)."\">&laquo;</a></li>";
    	$nxpage    = "<li><a href=\"".$url.($page+1)."\">下一页 &raquo;</a></li>";
    	if ($page <= 1){
    		$repage = "";
    	}
    	if ($page >= $howpage){
    		$nxpage = "";
    	}
    	if ($page > ($adjacents + 1)) {
    		$first = "<li><a href=\"".$url.'1'."\">1 ...</a></li>";
    	}
    	if ($page < ($howpage - $adjacents)){
    	    $last = "<li><a href=\"".$url.$howpage."\">... $howpage</a></li>";
    	}

    	$multipage = "";
    	$multipage = $first;
    	$multipage .= $repage;
    
    	//页数过多时
    	/*if (($howpage - $page) >= 10){
    		$howpage = 10;
    	}*/
    	for ($i=1; $i<=$howpage; $i++){  //页码
	    	if ($page == $i){
	    		$multipage .= "<li class=\"active\"><a href=\"#\">$i</a></li>";
	    	}elseif($page > ($i + $adjacents) || $page < ($i - $adjacents)){

	    	}else{
	    		$multipage .= "<li><a href=\"".$url.$i."\">$i</a></li>";
	    	}
    	}
    	$multipage .= $last;
    	$multipage .= $nxpage;
    
    	return $multipage;
    }
    
    //常用参数
    public function getConfig() {
        
        //价格范围
        $price = array("0"=>array("high"=>0,"name"=>"不限"),"1"=>array("low"=>0,"high"=>1,"name"=>"1万元以内"),"2"=>array("low"=>1,"high"=>2,"name"=>"1-2万"),"3"=>array("low"=>2,"high"=>3,"name"=>"2-3万"),"4"=>array("low"=>3,"high"=>5,"name"=>"3-5万"),"5"=>array("low"=>8,"high"=>12,"name"=>"8-12万"),"6"=>array("low"=>12,"high"=>18,"name"=>"12-18万"),"7"=>array("low"=>18,"high"=>24,"name"=>"18-24万"),"8"=>array("low"=>24,"high"=>40,"name"=>"24-40万"),"9"=>array("low"=>40,"high"=>9999,"name"=>"40万以上"));
        
        
        //车龄
        $age = array("0"=>array("high"=>0,"name"=>"不限"),"1"=>array("low"=>0,"high"=>1,"name"=>"1年以内"),"2"=>array("low"=>1,"high"=>3,"name"=>"1-3年"),"3"=>array("low"=>3,"high"=>5,"name"=>"3-5年"),"4"=>array("low"=>5,"high"=>8,"name"=>"5-8年"),"5"=>array("low"=>8,"high"=>10,"name"=>"8-10年"),"6"=>array("low"=>10,"high"=>9999,"name"=>"10年以上"));
        
        
        $year = date("Y");
        $sp_year = $year-20;
        //年份
        $start_arr = array();
        for ($i=$year;$i>=$sp_year;$i--){
            $start_arr[] = $i;
        }
        //$s_year = $year-5;
        $e_year = $year+4;
        $year_arr= array();
        for ($i=$e_year;$i>=$year;$i--){
            $year_arr[] = $i;
        }
        
        $month_arr = array("01"=>"01","02"=>"02","03"=>"03","04"=>"04","05"=>"05","06"=>"06","07"=>"07","08"=>"08","09"=>"09","10"=>"10","11"=>"11","12"=>"12");
        
        
        $question_arr = array(
            '1' => array('id' => '1', 'name' => "母亲的名字"),
            '2' => array('id' => '2', 'name' => "爷爷的名字"),
            '3' => array('id' => '3', 'name' => "父亲出生的城市"),
            '4' => array('id' => '4', 'name' => "您其中一位老师的名字"),
            '5' => array('id' => '5', 'name' => "您个人计算机的型号"),
            '6' => array('id' => '6', 'name' => "您最喜欢的餐馆名称"),
            '7' => array('id' => '7', 'name' => "驾驶执照最后四位数字"),
        );
        
        $config = array(
            'price'         => $price,
            'age'           => $age,
            'start_arr'     => $start_arr,
            'year_arr'      => $year_arr,
            'month_arr'     => $month_arr,
            'question_arr'  => $question_arr,
        );
        
        return $config;
    }
    
    //检查 我要卖车 输入
    public function checkSale($data) {
        
        $results[flag] = "0";
        $results[err_str] = "";
        
        if ($data[brand] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择车辆品牌。";
        }
        if ($data[model] == 0) {
        	$results[flag] = "1";
        	$results[err_str] .= "<br />请选择车系。";
        }
        //IS_WRITE 为0时 选择车型 否则手动输入
        if ($data[is_write] == 0) {
            if ($data[carname] == 0) {
                $results[flag] = "1";
                $results[err_str] .= "<br />请在列表中选择您的车型。";
            }
        }else{
            if ($data[model_text] == "" || $data[model_text] == "请在此输入车型名称") {
                $results[flag] = "1";
                $results[err_str] .= "<br />请在输入框中输入您的车型名称。";
            }
        }
        
        if ($data[color] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择车辆颜色。";
        }
        if ($data[province] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择车辆所在省份。";
        }
        if ($data[city] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择车辆所在城市。";
        }
        if ($data[kilometer] == "") {
            $results[flag] = "1";
            $results[err_str] .= "<br />请填写表显里程。";
        }elseif (!$this->isValidFloat($data[kilometer])){
            $results[flag] = "1";
            $results[err_str] .= "<br />表显里程格式错误。";
        }
        if ($data[car_year] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择上牌年份。";
        }
        if ($data[car_month] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择上牌月份。";
        }
        if ($data[check_year] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择年检有效期年份。";
        }
        if ($data[check_month] == 0 && $data[check_year] != -1) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择年检有效期月份。";
        }
        if ($data[safe_year] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择保检有效期年份。";
        }
        if ($data[safe_month] == 0 && $data[safe_year] != -1) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请选择保检有效期月份。";
        }
        if ($data[price] == 0) {
            $results[flag] = "1";
            $results[err_str] .= "<br />请填写预售价格。";
        }
        if ($data[contact_user] == "") {
            $results[flag] = "1";
            $results[err_str] .= "<br />请填写联系人名称。";
        }
        
        if ($data[contact_tel] == "") {
            $results[flag] = "1";
            $results[err_str] .= "<br />请填写联系手机。";
        }elseif (!$this->isValidFloat($data[contact_tel])){
            $results[flag] = "1";
            $results[err_str] .= "<br />>手机号码格式不正确。";
        }

        
        return $results;
    }
    
    //手机号码 11位验证
    public function CheckPhoneno($data){
        if(!preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|189[0-9]{8}$/", $data)){
            return false;
        }
        return true;
    }
    
    //判断是否为 身份证 含X
    public function isIdno($data){
        //$data = strval($data);
        if (!preg_match("/^[1-9]([0-9a-zA-Z]{17}|[0-9a-zA-Z]{14})$/", $data)){
            return false;
        }
        return true;
    }
    
    //判断 是否 为数字
    public function isValidFloat($data){
        $data = strval($data);
        if (preg_match('/^0[^.]/', $data)){
            return false;
        }
        if (preg_match('/^\d+(\.\d+)?$/', $data)){
            return true;
        }else{
            return false;
        }
    }
    
    //判断长度
    /*
     * @$C_cahr 字符 
     * @$I_len1 长度一
     * @$I_len2 长度二
     * 
     * */ 
    public function CheckLengthBetween($C_cahr, $I_len1, $I_len2=100)
    {
        $C_cahr = trim($C_cahr);
        if (strlen($C_cahr) < $I_len1) {
            return false;
        }
        if (strlen($C_cahr) > $I_len2) {
            return false;
        }
        return true;
    }
    //判断 中文长度
    public function CheckChineseLen($str)
    {      
        $n = 0; $p = 0; $c = '';
        $len = strlen($str);
        for($i = 0; $i < $len; $i++) {
            $c = ord($str{$i});
            if($c > 252) {
                $p = 5;
            } elseif($c > 248) {
                $p = 4;
            } elseif($c > 240) {
                $p = 3;
            } elseif($c > 224) {
                $p = 2;
            } elseif($c > 192) {
                $p = 1;
            } else {
                $p = 0;
            }
            $i+=$p;$n++;
        }     
        return $n;
    }
    
    //特殊字符检验 
    public function CheckSpecial($data){
        if (!preg_match("/^[_a-zA-Z0-9]*$/", $data)){
            return false;
        }
        return true;
    }
    //特殊字符检验 可以输入中文
    public function CheckSpecialCh($data){
        if (!preg_match("/^[_a-zA-Z0-9\x7f-\xff]*$/", $data)){
            return false;
        }
        return true;
    }

    //检查邮件是否合法
    public function CheckEmailAddr($C_mailaddr){
        if (!preg_match("/^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$/",$C_mailaddr)){
            return false;
        }
        return true;
    }
    
    //网址是否合法
    public function CheckWebAddr($C_weburl){
        if (!preg_match("/^http://[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$/", $C_weburl))
        {
            return false;
        }
        return true;
    }

    //检查是否为中文
    public function CheckChinese($data){
        if (preg_match("/[^\x80-\xff]/",$data)) {
            return true;
        }
        return false;
    }
    
    //截取中文 UFT8使用
    public function cutstr($string, $length, $dot = ' ...') {
        if(strlen($string) <= $length) {
            return $string;
        }
    
        $pre = chr(1);
        $end = chr(1);
        $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);
    
        $strcut = '';

    
            $n = $tn = $noc = 0;
            while($n < strlen($string)) {
    
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t <= 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
    
                if($noc >= $length) {
                    break;
                }
    
            }
            if($noc > $length) {
                $n -= $tn;
            }
    
            $strcut = substr($string, 0, $n);
    

    
        $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
    
        $pos = strrpos($strcut, chr(1));
        if($pos !== false) {
            $strcut = substr($strcut,0,$pos);
        }
        return $strcut.$dot;
    }
    
    //生成二维码
    public function getErweima($chl,$x ='230',$level='L',$margin='0'){
        /**
         * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本，具体可以查看二维码数据格式】
         * @param string $chl 二维码包含的信息，可以是数字、字符、二进制信息、汉字。不能混合数据类型，数据必须经过UTF-8 URL-encoded.如果需要传递的信息超过2K个字节，请使用POST方式
         * @param int $widhtHeight 生成二维码的尺寸设置
         * @param string $EC_level 可选纠错级别，QR码支持四个等级纠错，用来恢复丢失的、读错的、模糊的、数据。
         *                 L-默认：可以识别已损失的7%的数据
         *                 M-可以识别已损失15%的数据
         *                 Q-可以识别已损失25%的数据
         *                 H-可以识别已损失30%的数据
         * @param int $margin 生成的二维码离图片边框的距离
         */
        $img = '<img alt="正在努力生成二维码图像" src="http://chart.apis.google.com/chart?chs='.$x.'x'.$x.'&cht=qr&chld='.$level.'|'.$margin.'&chl='.urlencode($chl).'" />';
        return $img;
    }
    

    
    //生成验证码
    public function getCaptcha() {
        $tcl_session = new Zend_Session_Namespace('taochele');
        $captcha = new Zend_Captcha_Image();
        $height = rand(50, 100);//55
        
        $captcha->setTimeout('300')
                ->setWordLen('6')
                ->setHeight($height)
                ->setWidth('220')
                ->setFont('./data/fonts/calibri.ttf')
                ->setImgDir('./data/tmp/captcha/')
                ->setImgUrl('/data/tmp/captcha')
                ->setFontSize('35')
                ->setImgAlt('正在生成验证图片')
                ->setGcFreq('10'); //超过清理缓存图片
    
        $id = $captcha->generate();    //command to generate session + create image
        $tcl_session->captcha = strtoupper($captcha->getWord());// SESSION
        //echo $captcha->generate();
        //exit();
        /*
        $results = array(
            'captcha' => $captcha->generate().$captcha->getSuffix(),
            'id'      => $captcha->getId()
        );*/
        
        return $captcha->render();
    }
    
    //校验验证码
    public function validateCaptcha($captcha) {
        
        $tcl_session = new Zend_Session_Namespace('taochele');
        $captchaWord = $tcl_session->captcha;
    
        if($captchaWord) {
            if( $captchaWord != strtoupper($captcha) ){
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    
    }
    
    
    /* 登陆保护
     * 密码错误 3次 输出验证码 错误6次锁定15分钟
     * */
    public function protectLogin($username, $iserror=0) {
        //ISERROR 为 0  判断是否需要验证 为1时 验证错误次数+1
    	$login_num = $_COOKIE['loginnum_'.$username];
    	if ($iserror == 1){
    	    if (!$login_num > 6){
    	        //大于6之后  不在记录COOKIE 直到自动消毁

        	    if ($login_num){
        	    	//COOKIE 15分钟
        	    	setcookie('loginnum_'.$username, $login_num + 1, time() + 900);
        	    }else{
        	    	setcookie('loginnum_'.$username, 1);
        	    	$login_num = 1;
        	    }
    	    }
    	}

    	if ($login_num >= 3){
    		echo "<script>iscaptcha(1);</script>";
    	}else{
    	    echo "<script>iscaptcha(2);</script>";
    	}
    	if ($iserror ==1 && $login_num >= 6){
    	    if ($login_num == 6){
    	        //  15分钟锁定须入库 防止手动清除COOKIE
    	        setcookie('loginnum_'.$username, 7, time() + 900);
    	    }
    	    echo "<script>errorMsg(\"您的尝试次数过多,系统为了保护您的账号安全已经将您的账号<b>锁定15分钟</b>,如果您忘记密码<a href='/member/fogot'>点击此处</a><b>找回密码</b>。或者在<b>15分钟</b>后重新尝试登陆!\");</script>";
    	}
    	return $login_num;
    }

    
    public function checkUsername($value) {
        
        $res = 1;
        if (!$value){
            $res = "请输入用户名";
        }
        if ($this->isValidFloat($value)){
            $res =  "用户名不能全为数字";
        }
        if (!$this->CheckLengthBetween($value, 4, 20)){
            $res = "用户名长度需为4-20个字符";
        }
        if (!$this->CheckSpecialCh($value)){
            $res = "用户名中含有非法字符（仅可以使用汉字、数字、字母、下划线)";
        }
        //用户名 重复性
        $members = new Model_CommonMembers();
        if ($members->getUserByAccount($value)){
            $res = "该用户名已被注册,请使用其他用户名注册,如果您是 $value,<a href=\"/member/login/user/$value\">点击此处登陆</a>";
        }
        
        return $res;
    }
    
    public function checkPassword($value) {
        $res = 1;
        if (!$value){
            $res = "请输入密码";
        }
        if ($this->isValidFloat($value)){
            $res =  "密码不能全为数字";
        }
        if (!$this->CheckLengthBetween($value, 6, 50)){
            $res = "密码长度需为6-50个字符";
        }
        
        return $res;
    }
    
    public function checkEmail($value) {
        $res = 1;
        if (!$value){
            $res = "请输入常用邮箱";
        }
        if (!$this->CheckEmailAddr($value)){
            $res = "邮箱格式不正确";
        }
        //EMAIL 重复性
        $members = new Model_CommonMembers();
        if ($members->getUserByAccount($value)){
            $res = "该EMAIL已被注册,请使用其他EMAIL注册,如果您是 $value,<a href=\"/member/login/user/$value\">点击此处登陆</a>";
        }
        
        return $res;
    }
    
    public function checkCaptcha($value) {
        $res = 1;
        if (!$value){
            $res = "请输入验证字符";
        }
        if (!$this->validateCaptcha($value)){
            $res = "验证字符不正确,请重新输入";
            //echo "<script type=\"text/javascript\">getCaptcha();</script>";
        }
        return $res;
    }
    
    public function checkConame($value) {
        $res = 1;
        if (!$value){
            $res = "请输入公司名称";
        }
        if ($this->CheckChineseLen($value) < 6){
            $res = "公司名称长度需大于6个汉字";
        
        }
        if ($this->CheckChinese($value)){
            $res =  "公司名称必须为中文";
        }
        return $res;
    }
    
    public function checkCoaddress($value) {
        $res = 1;
        if (!$value){
            $res = "请输入公司地址";
        }
        if ($this->CheckChineseLen($value) < 10){
            $res = "请输入完整的公司地址";
        
        }
        return $res;
    }
    public  function checkRealname($value) {
        $res = 1;
        if ($this->CheckChinese($value)){
            $res = "请输入正确的姓名";
        }
        return $res;
    }
    
    public function checkIdcard($value) {
        $res = 1;
        if (!$this->isIdno($value)){
            $res = "身份证号码格式不正确";
        }
        return $res;
    }
    
    public function checkPhone($value) {
        $res = 1;
        if (!$this->CheckPhoneno($value)){
            $res = "手机号码格式不正确";
        }
        //手机号 重复性
        $members = new Model_CommonMembers();
        if ($members->getUserByAccount($value)){
        	$res = "该手机号码已被注册,请使用其他号码注册,如果您是 $value,<a href=\"/member/login/user/$value\">点击此处登陆</a>";
        }
        return $res;
    }
    
    public function checkLoginAccount($value) {
        $res = 1;
        if (!$value){
            $res = "账号不能为空";
        }
        $members = new Model_CommonMembers();
        $row = $members->getUserByAccount($value);
        if (!$row){
            $res = "账号不存在!";
        }
        return $res;
    }
    
    public function checkLoginPw($username, $password){
        $res = 1;
        if ($password){
	        $members = new Model_CommonMembers();
	        $row = $members->getUserByAccount($username);
	        if ($row[password] != $password){
	            $core = new Model_Core();
	            $login_num = $core->protectLogin($username, 1);
	        
	            $res = "密码错误,请重新输入!";
	            echo "<script>$(\"#inputPassword\").val('');</script>";
	            echo "<script type=\"text/javascript\">getCaptcha();</script>";
	        }
        }else{
            $res = "密码不能为空";
        }
         
        if ($login_num >= 6 && $username && $password){
            $res = "您的尝试次数过多,请稍后在试";
        }
        
        return $res;
    }
    
    //登陆验证
    public function checkLogin($data) {
        $results = "";
        $login_num = $_COOKIE['loginnum_'.$data[username]];

        if ($this->checkLoginAccount($data[username]) != 1){
            $results .= $this->checkLoginAccount($data[username])."<br/>";
        }
        if ($this->checkLoginPw($data[username], $data[password]) != 1){
            $results .= $this->checkLoginPw($data[username], $data[password])."<br/>";
        }
        if ($login_num >= 3){
            if ($this->checkCaptcha($data[captcha]) != 1){
                $results .= $this->checkCaptcha($data[captcha])."<br/>";
            }
        }
        
        if ($login_num >= 6 && $data[username]){
            $results = "您的尝试次数过多,系统为了保护您的账号安全已经将您的账号<b>锁定15分钟</b>,如果您忘记密码<a href='/member/fogot'>点击此处</a><b>找回密码</b>。或者在<b>15分钟</b>后重新尝试登陆!<br />";
        }
        
        return $results;
    }
    
    //注册验证
    public function checkRegister($data) {
    
        $results = "";
    
        if ($data[type] == 2){
            //商家
            if ($this->checkConame($data[coname]) != 1){
                $results .= $this->checkConame($data[coname])."<br/>";
            }
            if ($this->checkCoaddress($data[address]) != 1){
                $results .= $this->checkCoaddress($data[address])."<br/>";
            }
            if ($this->checkRealname($data[realname]) != 1){
                $results .= $this->checkRealname($data[realname])."<br/>";
            }
            if ($this->checkIdcard($data[idno]) != 1){
                $results .= $this->checkIdcard($data[idno])."<br/>";
            }
            if ($this->checkPhone($data[phone]) != 1){
                $results .= $this->checkPhone($data[phone])."<br/>";
            }

        }
        //所有规则
        if ($this->checkUsername($data[username]) != 1){
            $results .= $this->checkUsername($data[username])."<br/>";
        }
        if ($this->checkPassword($data[password]) != 1){
            $results .= $this->checkPassword($data[password])."<br/>";
        }
        if ($data[password] != $data[passwordagain]){
            $results .= "两次输入的密码不一致<br/>";
        }
        if ($this->checkEmail($data[email]) != 1){
            $results .= $this->checkEmail($data[email])."<br/>";
        }
        if ($this->checkCaptcha($data[captcha]) != 1){
            $results .= $this->checkCaptcha($data[captcha])."<br/>";
        }

        
        return $results;
    }
    
    //使用SESSION 进行登陆验证
    //是否登陆  登陆返回用户数组
    public function isLogin(){
        
        
        $tcl_session = new Zend_Session_Namespace('taochele');
        $uid = $tcl_session->uid;
        
        $memberdb = new Model_CommonMembers();
        if (!$uid) {
            $member = unserialize(stripslashes($_COOKIE['member']));

            //读取COOKIE 进行登陆
            if ($member){
                $islogin = $this->checkLoginPw($member[username], $member[password]);
                if ($islogin == 1){
                    if ($this->setLogin($member[uid], 604800)){
			            return $memberdb->getProfile($member[uid]);
                    }
                }
            }
            //没有COOKIE 返回失败
            //$ref = urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
            return false;
        }else{
            return $memberdb->getProfile($uid);
        }
    
    }
    
    
    //登陆COOKIE
    public function setLogin($uid, $time="") {
        if ($time){
            $member = new Model_CommonMembers();
            $db = $member->getByUid($uid);
            $member = array(
                'uid'      => $uid,
                'username' => $db[username],
                'password' => $db[password]
            );
            //unserialize
            setcookie("member", serialize($member), time() + $time, '/');
        }

        $tcl_session = new Zend_Session_Namespace('taochele');
        $tcl_session->uid = $uid;


        //$cookie = new Zend_Http_Cookie('uid', $uid, 'localhost', $time, '');
        return true;
    }
    
    //销毁 登陆 SESSION
    public function unsetLogin() {
        
        $tcl_session = new Zend_Session_Namespace('taochele');
        $tcl_session->__unset('uid');
        //清理COOKIE
        setcookie("member", "", 0, '/');
        return true;
    }
    
    
    //发送邮件
    public function sendMail($username, $address, $title, $content, $form="淘车乐") {
        
        $mail = new Zend_Mail('UTF-8');          // 设置编码
         
        $form_add = "members@taochele.com";
        // 配置邮件服务器信息
        $config = array(
            'auth'        => 'login',
            'username'    => $form_add,
            'password'    => 'Youxi005',
            'port'        => '25',
        );
         
        $transport    = new Zend_Mail_Transport_Smtp('smtp.exmail.qq.com', $config);
        
        // Initialize parameters
        $mail->setDefaultTransport($transport);         
        $mail->setBodyHtml($content);
        //$mail->setBodyText($mail_content);
        $mail->setFrom($form_add, $form);
        $mail->addTo("$address", "$username");
        $mail->setSubject($title);
        //$mail->setSubject("This is an example");
         
        try{
            $mail->send();
            return true;
        }catch(Zend_Mail_Exception $e){
            return $e->getMessage();
        }
    }
    
    //创建文件夹
    public function creatdir($dir){
        if(!file_exists($dir)){
            mkdir($dir, 0777, true);
            @chmod($dir, 511);//0777 八进制
        }
        return;
    }
    
    
    //生成缩略图
    public function cutphoto($o_photo,$d_photo,$width,$height){
    
    
    
        $temp_img = $this->imageCreateFromAny($o_photo);
        $o_width   = imagesx($temp_img);                                 //取得缩略图宽
        $o_height = imagesy($temp_img);
    
    
        //判断处理方法
        if($width >$o_width || $height>$o_height){         //原图宽或高比规定的尺寸小,进行压缩
    
            $newwidth=$o_width;
            $newheight=$o_height;
    
            if($o_width>$width){
                $newwidth=$width;
                $newheight=$o_height*$width/$o_width;
            }
    
            if($newheight>$height){
                $newwidth=$newwidth*$height/$newheight;
                $newheight=$height;
            }
    
            //缩略图片
            $new_img = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($new_img, $temp_img, 0, 0, 0, 0, $newwidth, $newheight, $o_width, $o_height);
            $this->saveimg($o_photo, $new_img , $d_photo);
            //imagejpeg($new_img , $d_photo);
            imagedestroy($new_img);
    
    
        }else{                                                                                 //原图宽与高都比规定尺寸大,进行压缩后裁剪
    
            if($o_height*$width/$o_width>$height){         //先确定width与规定相同,如果height比规定大,则ok
                $newwidth=$width;
                $newheight=$o_height*$width/$o_width;
                $x=0;
                $y=($newheight-$height)/2;
            }else{                                                                         //否则确定height与规定相同,width自适应
                $newwidth=$o_width*$height/$o_height;
                $newheight=$height;
                $x=($newwidth-$width)/2;
                $y=0;
            }
    
            //缩略图片
            $new_img = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($new_img, $temp_img, 0, 0, 0, 0, $newwidth, $newheight, $o_width, $o_height);
            $this->saveimg($o_photo, $new_img , $d_photo);
            //imagejpeg($new_img , $d_photo);
            imagedestroy($new_img);
    
    
            $temp_img = $this->imageCreateFromAny($d_photo);
            $o_width   = imagesx($temp_img);                                 //取得缩略图宽
            $o_height = imagesy($temp_img);
    
    
            //裁剪图片
            $new_imgx = imagecreatetruecolor($width,$height);
            imagecopyresampled($new_imgx,$temp_img,0,0,$x,$y,$width,$height,$width,$height);
            $this->saveimg($o_photo, $new_imgx , $d_photo);
            //imagejpeg($new_imgx , $d_photo);
            imagedestroy($new_imgx);
        }
    
    }
    
    
    //取得类型
    public function img_type($file){
        $type = getimagesize($file);
        return $type[mime];
    }
    
    public function imageCreateFromAny($filepath) {
    
        $type = $this->img_type($filepath);
        switch ($type) {
            case "image/gif" :
                $temp_img = imageCreateFromGif($filepath);
                break;
            case "image/jpeg" :
                $temp_img = imageCreateFromJpeg($filepath);
                break;
            case "image/png" :
                $temp_img = imageCreateFromPng($filepath);
                break;
            default:
                $temp_img = imageCreateFromJpeg($filepath);
                break;
        }
        return $temp_img;
    }
    
    
    public function saveimg($o_photo, $new_img , $d_photo){
    
    
        $type = $this->img_type($o_photo);
        switch ($type) {
            case "image/gif":
                imagegif($new_img , $d_photo);
                break;
            case "image/jpeg":
                imagejpeg($new_img , $d_photo);
                break;
            case "image/png":
                imagepng($new_img , $d_photo);
                break;
            default:
                imagejpeg($new_img , $d_photo);
                break;
        }
    
        return;
    }
    
    
    public function imageWaterMark($groundImage,$waterPos=0,$waterImage="",$waterText="",$textFont=5,$textColor="#FF0000")
    {
        $isWaterImage = FALSE;
        $formatMsg = "暂不支持该文件格式，请用图片处理软件将图片转换为GIF、JPG、PNG格式。";
    
        //读取水印文件
        if(!empty($waterImage) && file_exists($waterImage))
        {
            $isWaterImage = TRUE;
            $water_info = getimagesize($waterImage);
            $water_w    = $water_info[0];//取得水印图片的宽
            $water_h    = $water_info[1];//取得水印图片的高
    
            switch($water_info[2])//取得水印图片的格式
            {
                case 1:$water_im = imagecreatefromgif($waterImage);break;
                case 2:$water_im = imagecreatefromjpeg($waterImage);break;
                case 3:$water_im = imagecreatefrompng($waterImage);break;
                default:$water_im = imagecreatefrompng($waterImage);break;
            }
        }
    
        //读取背景图片
        if(!empty($groundImage) && file_exists($groundImage))
        {
            $ground_info = getimagesize($groundImage);
            $ground_w    = $ground_info[0];//取得背景图片的宽
            $ground_h    = $ground_info[1];//取得背景图片的高
    
            switch($ground_info[2])//取得背景图片的格式
            {
                case 1:$ground_im = imagecreatefromgif($groundImage);break;
                case 2:$ground_im = imagecreatefromjpeg($groundImage);break;
                case 3:$ground_im = imagecreatefrompng($groundImage);break;
                default:$ground_im = imagecreatefromjpeg($groundImage);break;
            }
        }
        else
        {
            echo "需要加水印的图片不存在！";
            return;
        }
    
        //水印位置
        if($isWaterImage)//图片水印
        {
            $w = $water_w;
            $h = $water_h;
            $label = "图片的";
        }
        else//文字水印
        {
            $temp = imagettfbbox(ceil($textFont*2.5),0,"./cour.ttf",$waterText);//取得使用 TrueType 字体的文本的范围
            $w = $temp[2] - $temp[6];
            $h = $temp[3] - $temp[7];
            unset($temp);
            $label = "文字区域";
        }
        if( ($ground_w<$w) || ($ground_h<$h) )
        {
            echo "需要加水印的图片的长度或宽度比水印".$label."还小，无法生成水印！";
            return;
        }
        switch($waterPos)
        {
            case 0://随机
                $posX = rand(0,($ground_w - $w));
                $posY = rand(0,($ground_h - $h));
                break;
            case 1://1为顶端居左
                $posX = 0;
                $posY = 0;
                break;
            case 2://2为顶端居中
                $posX = ($ground_w - $w) / 2;
                $posY = 0;
                break;
            case 3://3为顶端居右
                $posX = $ground_w - $w;
                $posY = 0;
                break;
            case 4://4为中部居左
                $posX = 0;
                $posY = ($ground_h - $h) / 2;
                break;
            case 5://5为中部居中
                $posX = ($ground_w - $w) / 2;
                $posY = ($ground_h - $h) / 2;
                break;
            case 6://6为中部居右
                $posX = $ground_w - $w;
                $posY = ($ground_h - $h) / 2;
                break;
            case 7://7为底端居左
                $posX = 0;
                $posY = $ground_h - $h;
                break;
            case 8://8为底端居中
                $posX = ($ground_w - $w) / 2;
                $posY = $ground_h - $h;
                break;
            case 9://9为底端居右
                $posX = $ground_w - $w;
                $posY = $ground_h - $h;
                break;
            default://随机
                $posX = rand(0,($ground_w - $w));
                $posY = rand(0,($ground_h - $h));
                break;
        }
    
        //设定图像的混色模式
        imagealphablending($ground_im, true);
    
        if($isWaterImage)//图片水印
        {
            imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件
        }
        else//文字水印
        {
            if( !empty($textColor) && (strlen($textColor)==7) )
            {
                $R = hexdec(substr($textColor,1,2));
                $G = hexdec(substr($textColor,3,2));
                $B = hexdec(substr($textColor,5));
            }
            else
            {
                die("水印文字颜色格式不正确！");
            }
            imagestring ( $ground_im, $textFont, $posX, $posY, $waterText, imagecolorallocate($ground_im, $R, $G, $B));
        }
    
        //生成水印后的图片
        @unlink($groundImage);
        switch($ground_info[2])//取得背景图片的格式
        {
            case 1:imagegif($ground_im,$groundImage);break;
            case 2:imagejpeg($ground_im,$groundImage);break;
            case 3:imagepng($ground_im,$groundImage);break;
            default:die($errorMsg);
        }
    
        //释放内存
        if(isset($water_info)) unset($water_info);
        if(isset($water_im)) imagedestroy($water_im);
        unset($ground_info);
        imagedestroy($ground_im);
    }
    
    public function setPicSession($session_id, $upload_num, $file_name) {
        
        //图片数组 SESSION
        
        
        $tcl_session = new Zend_Session_Namespace('taochele_'.$session_id);
        $pic_arr = $tcl_session->pic_arr;
        $pic_arr["SWFUpload_0_".$upload_num] = $file_name;
        
        $tcl_session->pic_arr = $pic_arr;
                        
        return true;
    }
    
    public function getPicSession($session_id) {
        $tcl_session = new Zend_Session_Namespace('taochele_'.$session_id);
        //$id = "arr_".$session_id;
        $res =  $tcl_session->pic_arr;
                
        return $res;
    }
    
    //判断是否为手机浏览
    public function is_mobile() {
    	$user_agent = $_SERVER['HTTP_USER_AGENT'];
    	$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
    	$is_mobile = false;
    	foreach ($mobile_agents as $device) {
    		if (stristr($user_agent, $device)) {
    			$is_mobile = true;
    			break;
    		}
    	}
    	return $is_mobile;
    }
   
}
